<template>
  <div class='mobile-file-wrapper'>
    <!-- 【注】 valid-tip-box 类名将作为paper页面的DOM索引，不能修改 -->
    <div class='valid-tip-box'
         v-if='question.validType === "required"'>
      请上传文件
    </div>
    <ul class='file-list'>
      <li class='file-item'
          v-for='(file, index) of question.fileArr'
          :key='index'
          @click='downloadFile(file)'>
        <span class='item-cover'
              v-if='file.type === "image"'
              :style='{backgroundImage: `url(${file.url || file.cover})`}'>
        </span>
        <span class='item-icon'
              v-else
              :class='{
                "survey-sprite-bg": file.type !== "pdf",
                video: file.type === "video",
                voice: file.type === "voice",
                pdf: file.type === "pdf",
                word: file.type === "word",
                ppt: file.type === "ppt",
                excel: file.type === "excel",
                other: file.type === "other"
              }'>
        </span>
        <span class='item-name'>{{file.name}}</span>
        <span class='item-del survey-sprite-bg'
              v-show='!isRecord'
              @click='delFile(index)'>
        </span>
      </li>
    </ul>
    <div class='file-box'
         v-show='(question.fileArr.length < question.maxCount) && !isRecord'
         @click='addFile'>
      <span class='file-icon survey-sprite-bg'></span>
      <span v-show='question.maxCount === 1'>选择文件（10M以内）</span>
      <span v-show='question.maxCount > 1'>选择文件（上限{{question.maxCount}}个，每个10M以内）</span>
    </div>
    <input
      class="file-uploader"
      type="file"
      @change="uploadFile"
      ref="fileIpt">
  </div>
</template>

<script>
import qiniuUploader from 'assets/upload/upload.js'
export default {
  name: 'mobileFile',
  data () {
    return {
    }
  },
  props: {
    question: {
      type: Object,
      default () {
        return {}
      }
    },
    isTest: {
      type: String,
      default: ''
    },
    isRecord: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    downloadFile (file) {
      if (this.isRecord && file.url) {
        window.open(file.url)
      }
    },
    resetValidType () {
      this.question.validType = ''
    },
    delFile (index) {
      this.question.fileArr.splice(index, 1)
      this.resetValidType()
    },
    uploadFile () {
      let file = this.$refs.fileIpt.files[0]
      console.log('file: ', file)
      // 单次上传不能超过10M
      let size = Math.floor(file.size / 1024)
      if (size > 1024 * 10) {
        this.$toast('文件大小不能超过10M')
        return false
      }
      // 如果文件类型有限制，则验证文件后缀名类型
      let typeArr = this.question.typeArr
      let fileType = file.name.split('.')[file.name.split('.').length - 1]
      console.log('fileType: ', fileType)
      if (!typeArr.filter(item => item === 'all')[0]) {
        if (!fileType) {
          this.$toast('文件类型不支持')
          return false
        } else {
          let isContain = typeArr.filter(item => {
            return item.indexOf(fileType.toLowerCase()) !== -1
          })[0]
          if (!isContain) {
            this.$toast('文件类型不支持')
            return false
          }
        }
      }
      // 添加上传的文件
      let newFile = {
        name: file.name,
        type: '',
        cover: '',
        url: ''
      }
      // 区分上传文件的类型
      if (!fileType) {
        newFile.type = 'other'
      } else {
        fileType = fileType.toLowerCase()
        if ('jpg/jpeg/png/gif'.indexOf(fileType) !== -1) {
          newFile.type = 'image'
          newFile.cover = window.URL.createObjectURL(file)
        } else if ('mp4/avi/mov/rmvb/rm/wmv/mpg/mpeg'.indexOf(fileType) !== -1) {
          newFile.type = 'video'
        } else if ('cda/wav/mp3/aif/aiff/mid/wma/amr'.indexOf(fileType) !== -1) {
          newFile.type = 'voice'
        } else if ('pdf'.indexOf(fileType) !== -1) {
          newFile.type = 'pdf'
        } else if ('doc/docx'.indexOf(fileType) !== -1) {
          newFile.type = 'word'
        } else if ('ppt/pptx'.indexOf(fileType) !== -1) {
          newFile.type = 'ppt'
        } else if ('xls/xlsx'.indexOf(fileType) !== -1) {
          newFile.type = 'excel'
        } else {
          newFile.type = 'other'
        }
      }
      console.log('isTest: ', this.isTest)
      if (this.isTest) {
        this.question.fileArr.push(newFile)
      } else {
        this.$_load.show()
        // 上传到七牛
        qiniuUploader.createQiniuUploader({
          file: file,
          nextCb: null,
          errorCb: null,
          completeCb: (res, baseConf) => {
            newFile.url = `${baseConf.domain}/${res.key}`
            this.$_load.hide()
            this.question.fileArr.push(newFile)
            console.log('this.question.fileArr: ', this.question.fileArr)
          }
        })
      }
    },
    addFile () {
      this.resetValidType()
      this.$refs.fileIpt.value = ''
      this.$refs.fileIpt.click()
    },
    init () {
      // 如果是查看记录模式, 回显答题记录
      if (this.isRecord) {
        console.log('record question: ', this.question)
        let answer = this.question.answer
        if (answer && answer[0] && answer[0].resultText) {
          this.question.fileArr = JSON.parse(answer[0].resultText)
        }
      }
    }
  },
  created () {
    console.log('file question: ', this.question)
    this.init()
  }
}
</script>

<style lang="stylus" scoped>
.mobile-file-wrapper
  margin-top 10px
  .valid-tip-box
    color #ef6262
    font-size 14px
    margin-bottom 5px
  .file-box
    display flex
    align-items center
    justify-content center
    max-width: 398px;
    height: 36px;
    box-sizing border-box
    border-radius: 4px;
    background-color: #fff;
    border: 1px solid #dde5ed;
    margin: 12px 0 0 0
    font-size: 12px;
    color: #484848;
    cursor pointer
    .file-icon
      display: inline-block;
      width: 24px;
      height: 24px;
      background-position: -360px -360px;
      margin-right: 6px;
      transform scale(0.8)
  .file-uploader
    display none
  .file-list
    .file-item
      position relative
      display flex
      align-items center
      border 1px solid #dde5ed
      height 36px
      box-sizing border-box
      padding 0 16px
      margin-bottom 10px
      .item-cover, .item-icon
        flex none
        margin-right 10px
        width 20px
        height 20px
      .item-cover
        bgCover()
      .item-icon
        &.video
          background-position -195px -362px
        &.voice
          background-position -171px -362px
        &.pdf
          background url('~assets/img/survey2.0/icon_file.png') no-repeat left 0 top 1px / 18px auto
        &.word
          background-position -243px -362px
        &.ppt
          background-position -291px -362px
        &.excel
          background-position -267px -362px
        &.other
          background-position -219px -362px
      .item-name
        flex 1
        width 0
        no-wrap()
        color #484848
        font-size 12px
      .item-del
        position absolute
        right -10px
        top -10px
        width 20px
        height 20px
        cursor pointer
        background-position -386px -170px
        transform scale(0.8)
</style>
